package com.naza.rpc.consumer.balance;

import com.naza.rpc.model.ServiceInstance;
import com.naza.rpc.util.AtomicPositiveInteger;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 轮询路由组件
 * @author yl
 */
public class RoundRobinLoadBalancer implements LoadBalancer {

    public static final RoundRobinLoadBalancer INSTANCE = new RoundRobinLoadBalancer();

    private ConcurrentHashMap<String, AtomicPositiveInteger> counters =
            new ConcurrentHashMap<String, AtomicPositiveInteger>();

    @Override
    public ServiceInstance selectClient(String serviceName, List<ServiceInstance> candidates) {
        if(null == candidates || candidates.size() == 0){
            return null;
        }
        AtomicPositiveInteger counter = new AtomicPositiveInteger();
        AtomicPositiveInteger existed = counters.putIfAbsent(serviceName, counter);
        if (existed != null) {
            counter = existed;
        }
        //轮询，自增值对候选者总数进行取余
        return candidates.get(counter.getAndIncrement() % candidates.size());
    }
}
